import json
import logging
import re
# 读取本地的JSON文件


def read_json_file(file_path):
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print("文件不存在！")
        return None
    except json.JSONDecodeError:
        print("JSON解码错误！")
        return None


# 将数据保存为JSON文件


def save_json_file(file_path, data, indent=4, separators=(", ", ": ")):
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(data, file, indent=indent, ensure_ascii=False, separators=separators)


# 生成ts接口
def generate_ts_interface(obj, code="interface xxx ", indent=""):
    if isinstance(obj, dict):
        code += "{\n"
        for key, value in obj.items():
            code += (
                f"  {indent}{key}: {generate_ts_interface(value,'',indent +'    ')};\n"
            )
        code += indent + "}"
    elif isinstance(obj, list):
        tmp = {}
        tmp_str = "("
        for value in obj:
            tmp[generate_ts_interface(value, "", "    ")] = 1
        for k, v in tmp.items():
            if tmp_str != "(":
                tmp_str += " | "
            tmp_str += k
        code += tmp_str + ")[]"
    else:
        code = get_ts_type(obj)
    return code


def get_ts_type(value):
    if isinstance(value, bool):
        return "boolean"
    elif isinstance(value, str):
        return "string"
    elif isinstance(value, int):
        return "number"
    else:
        return "any"


def dump_lua(data,indent = "    "):
    if type(data) is str:
        return f'"{data}"'
    if type(data) in (int, float):
        return f'{data}'
    if type(data) is bool:
        return data and "true" or "false"
    if type(data) is list:
        l = "{\n" + indent 
        l += (",\n" + indent).join([dump_lua(item,indent+"    ") for item in data])
        l +=  "\n"+ indent.replace("    ","",1) +"}"
        return l
    if type(data) is dict:
        t = "{\n" + indent 
        t += (",\n" + indent).join([f'[{re.escape(str(k))}] = {dump_lua(v,indent+"    ")}' if type(k) is int or k.isdigit() else  f'{re.escape(str(k))} = {dump_lua(v,indent+"    ")}' for k,v in data.items()])
        t += "\n"+ indent.replace("    ","",1) +"}"
        return t

    logging.error(f"Unknown type {type(data)}")



import hashlib
import requests
secret_key = "jkasdf1j391jkcjzlkdjq123"
def get_current_date_from_network():
    # 通过网络请求获取当前日期
    current_date = ""
    try:
        response = requests.get("http://worldtimeapi.org/api/ip")
        data = response.json()
        current_date = data.get("datetime", "")[:4]  # 提取日期部分
    except Exception as e:
        # 捕获异常，并不做任何处理
        print("111111111keyCode111111111111")
        pass
    
    return current_date

def generate_activation_code():
    # 获取当前日期，并格式化为字符串
    current_date = "2024" #get_current_date_from_network()

    # 拼接日期信息和其他激活码相关的数据
    data_to_hash = secret_key + current_date

    # 使用哈希算法生成激活码
    activation_code = hashlib.sha256(data_to_hash.encode()).hexdigest()

    return activation_code

def validate_activation_code(activation_code):
    # 获取当前日期，并格式化为字符串
    current_date = get_current_date_from_network()

    # 拼接日期信息和其他激活码相关的数据
    data_to_hash = secret_key + current_date

    # 使用哈希算法验证激活码
    expected_activation_code = hashlib.sha256(data_to_hash.encode()).hexdigest()

    # 检查生成的激活码是否与输入的激活码一致
    return activation_code == expected_activation_code

# # 生成激活码
# activation_code = generate_activation_code()
# print(f"Generated Activation Code: {activation_code}")

# # 模拟验证激活码
# is_valid = validate_activation_code(activation_code)
# print(f"Is Valid Activation Code: {is_valid}")
